package com.dou.sample.opengl_project;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;

import javax.microedition.khronos.opengles.GL10;

/**
 * Created by Dou on 2018/1/12.
 */

public class Square{

    // the vertexs
    private float[] vertexs = {
            -1, 1, 0, // 0, top left
            -1, -1, 0, // 1, bottom left
            1, -1, 0, // 2, top right
            1, 1, 0 // 3, bottom right
    };

    // the line order to connect them
    private short[] indicts = {
            0,1,2,0,2,3
    };

    // the vertex buffer
    public FloatBuffer vertexBuffer;

    // the index buffer
    private ShortBuffer indexBuffer;

    public Square(){
        ByteBuffer vertexByteBuffer = ByteBuffer.allocateDirect(vertexs.length * 4);
        vertexByteBuffer.order(ByteOrder.nativeOrder());
        vertexBuffer = vertexByteBuffer.asFloatBuffer();
        vertexBuffer.put(vertexs);
        vertexBuffer.position(0);

        ByteBuffer indexByteBuffer = ByteBuffer.allocateDirect(indicts.length * 2);
        indexByteBuffer.order(ByteOrder.nativeOrder());
        indexBuffer = indexByteBuffer.asShortBuffer();
        indexBuffer.put(indicts);
        indexBuffer.position(0);
    }

    public void draw(GL10 gl){
        gl.glFrontFace(GL10.GL_CCW);
        gl.glEnable(GL10.GL_CULL_FACE);
        gl.glCullFace(GL10.GL_BACK);

        // read vertex info
        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
        gl.glDrawElements(GL10.GL_TRIANGLES, indicts.length, GL10.GL_UNSIGNED_SHORT, indexBuffer);
        gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glDisable(GL10.GL_CULL_FACE);
    }
}
